﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using BusinessObjects.BO_GetObjects;
using BussinessObjects;
using BusinessObjects;
using LibraryO2S;
using System.IO;

public partial class controls_admin_NewsEdit : Pages_Base
{
    private int mid;
    private int aid;
    private DataTable objDT;
    protected void Page_Load(object sender, EventArgs e)
    {
        mid = base.getRequest("mid", -1);
        aid = base.getRequest("aid", -1);
        if (aid < 0)
            return;
        base.removeHGC(divMessage);
        if (!IsPostBack)
        {
            try
            {
                loadSetting();
                base.loadModuleByType(lsbModule, 1);
                base.loadModuleByType(lsbModule, 9);
                base.loadCategories(ddlCategories, 1);
                loadData();
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally { base.CloseConnection(); }
        }
    }
    private void loadData()
    {
        objDT = BO_Articles.Search(aid);
        if (objDT != null && objDT.Rows.Count > 0)
        {
            txtFULL_ARTICLE_TITLE.Text = objDT.Rows[0]["FULL_ARTICLE_TITLE"].ToString();
            txtFULL_ARTICLE_DESCRIPTION.Text = objDT.Rows[0]["FULL_ARTICLE_DESCRIPTION"].ToString();
            txtMetaKeyword.Text = objDT.Rows[0]["META_KEYWORD"].ToString();
            txtMetaDescription.Text = objDT.Rows[0]["META_DESCRIPTION"].ToString();
            ddlCategories.SelectedValue = objDT.Rows[0]["CATEGORY_ID"].ToString();
            cboDisplay.Checked = Convert.ToBoolean(objDT.Rows[0]["IS_DISPLAY_ON_HOME_PAGE"]);
            fkcContent.Value = objDT.Rows[0]["ARTICLE_DETAIL"].ToString();
            if (!objDT.Rows[0]["THUMB_IMG"].ToString().Equals(String.Empty))
                divImg.InnerHtml = "<img src='../upload/news/" + objDT.Rows[0]["THUMB_IMG"].ToString() + "' alt='" + objDT.Rows[0]["FULL_ARTICLE_TITLE"].ToString() + "' height='100' />";
            //Get Sort AND Set module
            string contain = "-1:";
            if (mid != -1)
            {
                DataTable moduleDT = BO_Module.Search(mid);
                if (moduleDT != null && moduleDT.Rows.Count > 0)
                {
                    string type = moduleDT.Rows[0]["TYPE_ID"].ToString();
                    if (type.Equals("1") || type.Equals("9") || type.Equals("8") || type.Equals("22"))
                        contain = mid.ToString() + ":";
                }
            }
            string sortdisplay = "1";
            string module_id = objDT.Rows[0]["MODULE_ID"].ToString();
            string[] list_module = module_id.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
            foreach (string per_m_id in list_module)
            {
                foreach (ListItem item in lsbModule.Items)
                    if (item.Value.Equals(per_m_id.Split(new char[] { ':' }, StringSplitOptions.RemoveEmptyEntries)[0]))
                        item.Selected = true;
                if (per_m_id.StartsWith(contain))
                    sortdisplay = per_m_id.Remove(0, contain.Length);
            }
            txtSortDisplay.Text = sortdisplay;
            //END Get Sort AND Set module
        }
        else
            divMessage.InnerHtml = O2S_Message.Warning("Hệ Thống", "Bản ghi này không tồn tại hoặc đã bị xóa.");
    }
    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        try
        {
            objDT = BO_Articles.Search(aid);
            string filename = objDT.Rows[0]["THUMB_IMG"].ToString();
            try
            {
                if (fulTHUMB_IMG.HasFile)
                {
                    filename = fulTHUMB_IMG.FileName;
                    int count = 0;
                    while (File.Exists(Server.MapPath("~/upload/news/") + filename))
                    {
                        filename = count + "_" + fulTHUMB_IMG.FileName;
                        count++;
                    }
                    fulTHUMB_IMG.SaveAs(Server.MapPath("~/upload/news/") + filename);
                }
            }
            catch (Exception ex)
            {
                divMessage.InnerHtml = O2S_Message.Error("Hệ Thống", "Lỗi ghi file! " + ex.Message);
                return;
            }
            int module_id = Convert.ToInt32(ddlCategories.SelectedValue);
            int status = 1;
            string title = txtFULL_ARTICLE_TITLE.Text.Trim();
            string full_article_description = txtFULL_ARTICLE_DESCRIPTION.Text.Trim();
            string details = fkcContent.Value;
            string m_key = txtMetaKeyword.Text.Trim();
            string m_desc = txtMetaDescription.Text.Trim();
            bool displayOnHome = cboDisplay.Checked;
            DataTable admin = (DataTable)Session["Admin"];
            string sort_display = txtSortDisplay.Text.Trim();
            string category_id = ";";
            string contain = "-1:";
            if (mid != -1)
            {
                DataTable module = BO_Module.Search(mid);
                string type = module.Rows[0]["TYPE_ID"].ToString();
                if (type.Equals("1") || type.Equals("9") || type.Equals("8") || type.Equals("22"))
                    contain = mid.ToString() + ":";
            }
            string old_mid = objDT.Rows[0]["MODULE_ID"].ToString();
            if (!old_mid.StartsWith(";-1:"))
                old_mid = ";-1:" + sort_display + old_mid;
            string[] perstr = old_mid.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
            if (contain.Equals("-1:"))
                category_id += perstr[0].Remove(contain.Length) + sort_display + ";";
            else
                category_id += perstr[0] + ";";
            string str = string.Empty;
            foreach (ListItem item in lsbModule.Items)
            {
                if (item.Selected)
                {
                    string itemSelected = item.Value + ":";
                    if (itemSelected.Equals(contain))
                        str = contain + sort_display;
                    else
                    {
                        str = itemSelected + sort_display;
                        foreach (string per in perstr)
                        {
                            if (per.StartsWith(itemSelected))
                            {
                                str = per;
                                break;
                            }
                        }
                    }
                    category_id += str + ";";
                }
            }
            string strResult = BO_Articles.Update(aid, module_id, "",
                    2, "", filename, "", "", title, "", "", "", full_article_description, "", details, "", "", m_key, m_desc, 0,
                    0, 0, 0, displayOnHome, category_id,
                    DateTime.Now, admin.Rows[0]["USER_NAME"].ToString(), DateTime.Now, "", status);
            if (strResult != "0")
                divMessage.InnerHtml = O2S_Message.Success("Thông Báo", "Cập nhật thành công!");
            else
                divMessage.InnerHtml = O2S_Message.Error("Lỗi", "Có lỗi trong quá trình xử lý!");
        }
        catch (Exception ex)
        {
            throw ex;
        }
        finally { base.CloseConnection(); }
    }
    private void loadSetting()
    {
        DataTable objDT = BO_Settings.SelectByGroupId(3, 1);
        foreach (DataRow dr in objDT.Rows)
        {
            string value = dr["SETTING_VALUE"].ToString();
            switch (dr["SETTING_KEY"].ToString())
            {
                case "NOTE_CATE":
                    NOTE_CATE.InnerText = value;
                    break;
                case "NOTE_DISPLAY":
                    NOTE_DISPLAY.InnerText = value;
                    break;
                case "NOTE_MODULE":
                    NOTE_MODULE.InnerText = value;
                    break;
                case "NOTE_SORT":
                    NOTE_SORT.InnerText = value;
                    break;
                case "NOTE_TITLE":
                    NOTE_TITLE.InnerText = value;
                    break;
                case "NOTE_DESCRIPT":
                    NOTE_DESCRIPT.InnerText = value;
                    break;
                case "NOTE_URL":
                    NOTE_URL.InnerText = value;
                    break;
            }
        }
    }
}
